package org.njbdqn.mybuy.database;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SqlTemplate {
	private DbManager dbm;
	
	public int update(String sql,Object [] params){
		dbm = new DbManager();
		int count = dbm.update(sql, params);
		dbm.destory();
		return count;
	}
	
	public <T>List<T> resultToArray(String sql,Object [] params,Class cls){
		dbm = new DbManager();
		List<T> lst = new ArrayList<T>();
		ResultSet rs = dbm.query(sql, params);
		try {
			while (rs.next()) {
				Object obj = cls.newInstance();
				Field [] fields = cls.getDeclaredFields();
				for(Field field : fields){
					field.setAccessible(true);
					field.set(obj, rs.getObject(field.getName()));
				}
				lst.add((T) obj);
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbm.destory();
		return lst;
	}
	
	public Object resultToObject(String sql,Object [] params){
		dbm = new DbManager();
		Object res= null;
		ResultSet rs = dbm.query(sql, params);
		try {
			if (rs.next()) {
				res = rs.getObject(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbm.destory();
		return res;
	}
}
